<template>
	<view class="main-container">
		<view class="top-control">
			<view class="control-item">
				<view v-if="!isEditNow" @click="isEditNow = !isEditNow">
					<uni-icons type="gear" size="16" color="#ff5a00"></uni-icons>管理
				</view>
				<view v-else @click="isEditNow = !isEditNow">
					<uni-icons type="undo" size="16" color="#ff5a00"></uni-icons>退出管理
				</view>
			</view>
			<view class="control-item" @click="toAddNewAddress" v-if="!isEditNow">
				<uni-icons type="plusempty" size="16" color="#ff5a00"></uni-icons>新增地址
			</view>
		</view>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback" :up="upOption"
			:bottom="50">
			<!-- // @init="mescrollInit" @down="downCallback" @up="upCallback"为固定值,不可删改(与mescroll-mixins保持一致)
			// :down="downOption" :up="upOption" 绝大部分情况无需配置
			// :top="顶部偏移量" :bottom="底部偏移量" :topbar="状态栏" :safearea="安全区" (常用)
			// 此处支持写入原生组件 -->
			<uni-card :class="selectedIndex === index ? 'selected-card' : ''" v-for="(item, index) in list" :key="item.id"
				margin="0" @click.stop="selectThisAddress(item.id, index)">
				<view slot="title">
					<view @click.stop="selectThisAddress(item.id, index)">
						<uni-section :title="'收货人：' + item.name">
							<template v-slot:right>
								{{item.phone}}
								<uni-tag style="margin-left: 20rpx;" size="mini" v-if="item.isdefault === 1" text="默认" type="warning" />
							</template>
						</uni-section>
					</view>
				</view>
				<text class="uni-body uni-mt-5">收货地址：{{item.city}} {{item.detail}}</text>
				<view slot="actions" class="cart-footer" v-if="isEditNow">
					<view class="set-default" @click="setThisDefault(item)">
						<uni-icons :color="item.isdefault === 1 ? '#ff5a00' : '#c4c6c9'"
							:type="item.isdefault === 1 ? 'circle-filled' : 'circle'" size="20"></uni-icons>
						<text
							:style="{'color': item.isdefault === 1 ? '#ff5a00' : '#c4c6c9'}">{{item.isdefault === 1 ? "默认地址" : "设为默认"}}</text>
					</view>
					<view class="card-actions">
						<view class="card-actions-item" @click="editThis(item)">
							<uni-icons type="compose" size="18" color="#c4c6c9"></uni-icons>
							<text class="card-actions-item-text">编辑</text>
						</view>
						<view class="card-actions-item" @click="deleteAddress(item.id)">
							<uni-icons type="trash" size="18" color="#c4c6c9"></uni-icons>
							<text class="card-actions-item-text">删除</text>
						</view>
					</view>
				</view>
			</uni-card>
		</mescroll-body>
		<view class="addNewButton">
			<u-button v-if="isSelect && addressId" text="提交修改" shape="circle" icon="plus-circle-fill" type="error"
				@click="selectConfirm"></u-button>
		</view>
	</view>
</template>

<script>
	import {
		getAddressList,
		setDefault,
		removeAddress
	} from "@/utils/wx_address"
	// 引入mescroll-mixins.js
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				list: [],
				isEditNow: false,
				isSelect: false,
				addressId: "",
				selectedIndex: undefined,
				upOption: {
					noMoreSize: 5,
					textNoMore: "-- 没有更多 --",
					toTop: {
						offset: 200
					}
				}
			}
		},
		onLoad(options) {
			if (options.flag === "select") {
				this.isSelect = true;
			} else {
				this.isSelect = false
			}
		},
		onShow() {
			this.refreshList()
		},
		methods: {
			toAddNewAddress() {
				uni.navigateTo({
					url: "/pages/mine/address/setting"
				})
			},
			selectThisAddress(id, index) {
				// console.log('select')
				if (this.isSelect) {
					this.addressId = id
					this.selectedIndex = index
				}
			},
			selectConfirm() {
				uni.$emit('selectedAddressId', this.addressId)
				uni.navigateBack()
			},
			async setThisDefault(item) {
				if (item.isDefault !== 1) {
					uni.showModal({
						title: "提示",
						content: "要将此地址设为默认吗？",
						success: async (res) => {
							if (res.confirm) {
								let res = await setDefault({
									id: item.id
								})
								uni.showToast({
									icon: 'success',
									title: '设置默认成功',
									success: () => {
										this.isEditNow = !this.isEditNow
										this.refreshList()
									}
								})
							} else {
								console.log('取消')
							}
						}
					})
				}
			},
			async deleteAddress(id) {
				try {
					uni.showModal({
						title: "提示",
						content: "确定要删除此地址吗",
						success: async (res) => {
							if(res.confirm){
								let res = await removeAddress({
									id: id
								})
								uni.showToast({
									icon: 'success',
									title: '删除成功',
									success: () => {
										this.refreshList()
									}
								})
							}
						}
					})
				} catch (e) {
					console.log(e)
					//TODO handle the exception
				}
			},
			editThis(data){
				uni.navigateTo({
					url: "/pages/mine/address/setting?data=" + encodeURIComponent(JSON.stringify(data))
				})
			},
			/*上拉加载的回调*/
			refreshList(keywords) {
				// console.log(keywords, 'keywords');
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				})
				this.keywords = keywords
				this.mescroll.resetUpScroll();

			},
			upCallback(page) {
				// console.log("upcallback")
				this.getMyList(page)
			},
			async getMyList(page) {
				try {
					let res = await getAddressList({
						pageSize: page.size,
						currentPage: page.num,
						openid: uni.getStorageSync('openid')
					});
					// console.log(res);
					let pageNum = page.num; // 页码, 默认从1开始
					let pageSize = page.size; // 页长, 默认每页10条
					let curPageData = res.data.rows;
					let curPageLen = curPageData.length;
					let totalSize = res.data.total;
					let totalPage = Math.ceil(totalSize / page.size);
					let hasNext = true
					if (res.data.rows.length < page.size) {
						hasNext = false
					} else {
						hasNext = true
					}
					if (page.num == 1) {
						this.list = []
					}
					this.list = this.list.concat(curPageData)
					this.mescroll.endByPage(curPageLen, totalPage);
				} catch (err) {
					console.log(err, '获取项目列表失败');
					this.mescroll.endErr()
				}
			},
		}
	}
</script>


<style scoped lang="scss">
	.main-container {
		background-color: #f7f7f7;
		min-height: 100vh;
		box-sizing: border-box;
		padding: 0 3vw;
	}

	/deep/ .top-control {
		display: flex;
		align-items: center;
		padding-top: 20rpx;
		justify-content: flex-end;
		color: #ff5a00;

		.control-item {
			margin-left: 30rpx;
			display: flex;
			align-items: center;
		}
	}

	.addNewButton {
		position: fixed;
		width: 90vw;
		left: 5vw;
		bottom: 50rpx;
	}

	/deep/ .selected-card {
		.uni-card {
			border: 1px solid #ff5a00 !important;
		}
	}

	/deep/.uni-card {
		margin-top: 30rpx !important;
		padding: 20rpx !important;

		.card-actions {
			width: 30%;
			display: flex;
			flex-direction: row;
			justify-content: space-around;
			align-items: center;
			height: 45px;
		}

		.cart-footer {
			padding: 0 20rpx;
			border-top: 1px solid #eee;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.set-default {
				display: flex;
				align-items: center;
				font-size: 26rpx;
			}
		}
	}
</style>